parameters:
  - name: VSCODE_CLI_ARTIFACTS
    type: object
    default: []

steps:
  - task: AzureKeyVault@1
    displayName: "Azure Key Vault: Get Secrets"
    inputs:
      azureSubscription: "vscode-builds-subscription"
      KeyVaultName: vscode-build-secrets
      SecretsFilter: "ESRP-PKI,esrp-aad-username,esrp-aad-password"

  - task: UseDotNet@2
    inputs:
      version: 6.x

  - task: EsrpClientTool@1
    displayName: "Use ESRP client"

  - ${{ each target in parameters.VSCODE_CLI_ARTIFACTS }}:
      - task: DownloadPipelineArtifact@2
        displayName: Download artifact
        inputs:
          artifact: ${{ target }}
          path: $(Build.ArtifactStagingDirectory)/pkg/${{ target }}

      - task: ExtractFiles@1
        displayName: Extract artifact
        inputs:
          archiveFilePatterns: $(Build.ArtifactStagingDirectory)/pkg/${{ target }}/*.zip
          destinationFolder: $(Build.ArtifactStagingDirectory)/sign/${{ target }}

  - powershell: |
      . build/azure-pipelines/win32/exec.ps1
      $ErrorActionPreference = "Stop"
      $EsrpClientTool = (gci -directory -filter EsrpClientTool_* $(Agent.RootDirectory)\_tasks | Select-Object -last 1).FullName
      $EsrpCliZip = (gci -recurse -filter esrpcli.*.zip $EsrpClientTool | Select-Object -last 1).FullName
      mkdir -p $(Agent.TempDirectory)\esrpcli
      Expand-Archive -Path $EsrpCliZip -DestinationPath $(Agent.TempDirectory)\esrpcli
      $EsrpCliDllPath = (gci -recurse -filter esrpcli.dll $(Agent.TempDirectory)\esrpcli | Select-Object -last 1).FullName
      echo "##vso[task.setvariable variable=EsrpCliDllPath]$EsrpCliDllPath"
    displayName: Find ESRP CLI

  - powershell: node build\azure-pipelines\common\sign $env:EsrpCliDllPath sign-windows $(ESRP-PKI) $(esrp-aad-username) $(esrp-aad-password) $(Build.ArtifactStagingDirectory)/sign "*.exe"
    displayName: Codesign

  - ${{ each target in parameters.VSCODE_CLI_ARTIFACTS }}:
      - powershell: |
          $ASSET_ID = "${{ target }}".replace("unsigned_", "");
          echo "##vso[task.setvariable variable=ASSET_ID]$ASSET_ID"
        displayName: Set asset id variable

      - task: ArchiveFiles@2
        displayName: Archive signed files
        inputs:
          rootFolderOrFile: $(Build.ArtifactStagingDirectory)/sign/${{ target }}
          includeRootFolder: false
          archiveType: zip
          archiveFile: $(Build.ArtifactStagingDirectory)/$(ASSET_ID).zip

      - task: 1ES.PublishPipelineArtifact@1
        inputs:
          targetPath: $(Build.ArtifactStagingDirectory)/$(ASSET_ID).zip
          artifactName: $(ASSET_ID)
          sbomBuildDropPath: $(Build.ArtifactStagingDirectory)/sign/${{ target }}
          sbomPackageName: "VS Code Windows ${{ target }} CLI"
          sbomPackageVersion: $(Build.SourceVersion)
        displayName: Publish signed artifact with ID $(ASSET_ID)
